<template>
    <div>
      <KTBlankTab v-bind:title="'Select File'">
          <template v-slot:preview>
            <b-row>
                <b-col cols="10">
                  <p>
                    Please select the files for CK measurement, limited to XML files:
                  </p>
                  <b-form-file multiple @change="onFileSelected" accept=".xml">
                    <template slot="file-name" slot-scope="{ names }">
                      <b-badge variant="dark">{{ names[0] }}</b-badge>
                      <b-badge v-if="names.length > 1" variant="dark" class="ml-1">
                        + {{ names.length - 1 }} More files
                      </b-badge>
                    </template>
                  </b-form-file>
                </b-col>
                <b-col cols="2">
                  <div>
                    <p>
                      &nbsp;
                    </p>
                          <div class="text-center">
                            <div class="my-2">
                              <v-btn color="#1bc5bd" dark v-on:click="CKAnalysis">Upload</v-btn>
                            </div>
                          </div>
                  <!-- <b-button class="mr-3" variant="outline-primary" v-on:click="CKAnalysis">Upload</b-button> -->
                </div>
                </b-col>
              </b-row>
            
          </template>
        </KTBlankTab>
  
      <div class="row" data-app="true">
        <div class="col-md-12">
          <KTTab v-bind:title="'CK'">
            <template v-slot:preview>
              <p>
                The results of the CK metric are given below:
              </p>
              <v-card>
                <v-card-title>
                  CK Metric
                  <v-spacer></v-spacer>
                  <v-text-field
                    v-model="code4.search"
                    append-icon="search"
                    label="Search"
                    single-line
                    hide-details
                  ></v-text-field>
                </v-card-title>
                <v-data-table
                  :headers="code4.headers"
                  :items="code4.classes"
                  :search="code4.search"
                >
                <template v-slot:item.name="{ item }">
                  <!-- 在这里定义第一列的渲染方式 -->
                  <!-- 以 <a> 标签为例 -->
                  <a href="#" @click.stop="showdialog(item.name)">{{ item.name }}</a>
                </template>
                </v-data-table>
              </v-card>
            </template>
          </KTTab>
              <v-dialog v-model="dialog" max-width="1000">
                <v-card>
                  <b-row no-gutters>
                    <b-col md="5">
                      <div style="margin-left: 1rem;">
                            <v-card-title class="headline"
                              >Data</v-card-title
                            >
                            <div id="chart">
                              <apexchart type="bar" height="350" :options="chartOptions2" :series="series2"></apexchart>
                            </div>
                      </div>
                    </b-col>
                    <b-col md="7">
                      <div style="margin-top: 2rem;margin-right: 2rem;margin-left: 2rem;">
                        <img
                            src="media/stock-600x600/img-0.png"
                            alt="Placeholder Image"
                            style="display: none"
                          />
                      <b-media>
                        <template v-slot:aside>
                          <b-img
                            thumbnail
                            src="media/stock-600x600/img-0.png"
                            width="50"
                          ></b-img>
                        </template>
                        <h5 class="mt-0">Analysis</h5>
                        <ul style="margin-left: 2rem;">
                          <li v-for="(item, index) in chatGPTtoShow[0].analysis.split('\n\n')" :key="index" style="margin-bottom: 0.8rem;">
                            <span v-html="boldText(item)"></span>
                          </li>
                        </ul>
                      </b-media>
                      </div>
                    </b-col>
                  </b-row>
                  <v-card-actions>
                          <v-spacer></v-spacer>
                          <v-btn
                            color="green darken-1"
                            text
                            @click="dialog = false"
                          >
                            OK
                          </v-btn>
                        </v-card-actions>
                </v-card>
              </v-dialog>
        </div>
      </div>
      <KTTab v-bind:title="'CK'">
            <template v-slot:preview>
              <div id="chart">
                <apexchart type="line" height="350" :options="chartOptions" :series="series"></apexchart>
              </div>
            </template>
      </KTTab>
    </div>
  </template>
  
  <script>
  import KTTab from "@/view/content/Tab.vue";
  import KTBlankTab from "@/view/content/BlankTab.vue";
  import { SET_BREADCRUMB } from "@/core/services/store/breadcrumbs.module";
  import{ getCK, uploadXML, chatGPTAnalysis } from "@/api/ck.js";


  export default {
    data() {
      return {
        files : null,
        dialog : false,
        code4: {
          search: "",
          headers: [
            {
              text: "Class Name (类名)",
              align: "left",
              sortable: false,
              value: "name"
            },
            { text: "WMC", value: "wmc" },
            { text: "RFC", value: "rfc" },
            { text: "DIT", value: "dit" },
            { text: "NOC", value: "noc" },
            { text: "CBO", value: "cbo" },
            { text: "LCOM", value: "lcom" }
          ],
          classes: [
          ]
        },
        chartOptions: {
            chart: {
              height: 350,
              type: 'line',
              zoom: {
                enabled: false
              },
            },
            dataLabels: {
              enabled: false
            },
            title: {
              text: 'Data Plot',
              align: 'left'
            },
            legend: {
              tooltipHoverFormatter: function(val, opts) {
                return val + ' - <strong>' + opts.w.globals.series[opts.seriesIndex][opts.dataPointIndex] + '</strong>'
              }
            },
            markers: {
              size: 0,
              hover: {
                sizeOffset: 6
              }
            },
            xaxis: {
              categories: ['WMC', 'RFC', 'DIT', 'NOC', 'CBO', 'LCOM'
              ],
            },
            tooltip: {
              y: [
                {
                  title: {
                    formatter: function (val) {
                      return val;
                    }
                  }
                }
              ]
            },
            grid: {
              borderColor: '#f1f1f1',
            }
          },
        series: [],
        series2: [{
            data: [0, 0, 0, 0, 0, 0]
          }],
        chartOptions2: {
          colors: ['#1BC5BD'],
          chart: {
            type: 'bar',
            height: 350
          },
          plotOptions: {
            bar: {
              borderRadius: 4,
              horizontal: true,
            }
          },
          dataLabels: {
            enabled: false
          },
          xaxis: {
            categories: ['WMC', 'RFC', 'DIT', 'NOC', 'CBO', 'LCOM'],
          }
        },
        chatGPT:[{name: "", analysis: ""}],
        chatGPTtoShow: [{analysis:"AI分析还在进行中,请稍后。。。"}]
      };
    },
    methods : {
      boldText(text) {
      // 定义要加粗的关键词
      const boldKeywords = ['WMC', 'RFC', 'DIT', 'NOC', 'CBO', 'LCOM'];

      // 使用正则表达式替换文本中的关键词为加粗的格式
      boldKeywords.forEach(keyword => {
        const pattern = new RegExp(`\\*\\*${keyword} \\([^\\)]+\\)\\*\\*`, 'g'); // 匹配 **WMC (xxx)** 格式的关键词
        text = text.replace(pattern, `<b>${keyword} </b>`); // 删除双星号，并添加加粗标签
      });

      return text;
      },
      showdialog(name){
        event.preventDefault();

        this.series2 = this.series
        .filter(item => item.name === name)  
        .map(item => ({ data: item.data }));

        let resp = this.chatGPT
        .filter(item => item.name === name)
        .map(item => ({ analysis: item.analysis }));
        console.log(this.chatGPT)
        console.log(name);
        if (resp && resp.length > 0) {
          this.chatGPTtoShow = resp; 
        } else {
          this.chatGPTtoShow = [{analysis:"AI分析还在进行中,请稍后。。。"}];
        }
        
        console.log(this.chatGPTtoShow);

        this.dialog = true;
      },
      onFileSelected(event) {
        this.files = event.target.files
        console.log(this.files)
      },
      CKAnalysis() {
        console.log("上传文件")
        if (!this.files) {
          return
        }
        let formData = new FormData()
        formData.append('file', this.files[0])
        uploadXML(formData).then(resp => {
          console.log("上传成功")
          let fileName = resp.data.FILENAME

          getCK(fileName).then(resp => {
           console.log("OK");
           this.code4.classes = resp.data;
           const metrics = ['wmc', 'rfc', 'dit', 'noc', 'cbo', 'lcom'];
           this.series = resp.data.map((item) => ({
            name: item.name,
            data:  metrics.map(metric => item[metric]) 
           }));

           this.series.forEach(item => {
                let message = [{"类名":item.name,
                                "WMC":item.data[0],
                                "RFC":item.data[1],
                                "DIT":item.data[2],
                                "NOC":item.data[3],
                                "CBO":item.data[4],
                                "LCOM":item.data[5]}];
                let formData2 = new FormData();
                formData2.append('CKResult', JSON.stringify(message));
                chatGPTAnalysis(formData2).then(resp => {
                    this.chatGPT.push({ name: item.name, analysis: resp.data.MSG });
                });
            });
          })
        })
      }
    },
    components: {
      KTTab,
      KTBlankTab,
    },
    mounted() {
      this.$store.dispatch(SET_BREADCRUMB, [
        { title: "OOM", route: "OOM" },
        { title: "CK" }
      ]);
      const img = new Image();
      img.src = "media/stock-600x600/img-0.png";
    }
  };
  </script>
  <style>
    @import url("https://unpkg.com/dropzone@5/dist/min/dropzone.min.css");
  </style>
  